<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="openDialog('add')">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-select v-model="selectedFilter" placeholder="请选择状态" style="width: 200px;">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="2"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" style="width: 200px;" />
        <el-button type="info" @click="query">查询</el-button>
        <el-button type="info" @click="reset">重置</el-button>
      </div>
      <el-table :data="filteredTableData" border class="eltable" ref="table" :row-key="rowKey">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index"  label="序号" width="80"></el-table-column>
        <el-table-column prop="cp_code" label="产品编码"></el-table-column>
        <el-table-column prop="cp_name" label="产品名称"></el-table-column>
        <el-table-column prop="pp_name" label="产品品牌"></el-table-column>
        <el-table-column prop="cp_flname" label="产品分类"></el-table-column>
        <el-table-column prop="cp_xh" label="产品型号"></el-table-column>
        <el-table-column prop="dw_name" label="产品单位"></el-table-column>
        <el-table-column prop="cp_lxname" label="产品类型"></el-table-column>
        <el-table-column prop="bom_code" label="制造BOM" width="170">
          <template #default="{ row }">
            <el-button type="text" @click="showBOMDetails(row)">{{ row.bom_code }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="cp_state" label="启用">
          <template #default="{ row }">
            <el-switch :model-value="row.cp_state === 1" @click="onStatusChange(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="text" @click="ck(row)">查看</el-button>
            <el-button type="text" @click="openDialog('edit', row)">编辑</el-button>
            <el-button type="text" @click="confirmDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper" class="el-pagination">
      </el-pagination>
      <el-loading :loading="loading" text="加载中..."></el-loading>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

const API_URL = '/api/BD_CP';

export default {
  setup() {
    const tableData = ref([]);
    const loading = ref(false);
    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(0);
    const router = useRouter();
    const uid = ref('');
    //获取数据
    const fetchData = async () => {
      loading.value = true;
      try {
        const res = await axios.get(`${API_URL}/GetBD_CP`);
        tableData.value = res.data;
        totalItems.value = tableData.value.length;
      } catch (error) {
        console.error('Error fetching tableData:', error);
        ElMessage.error('数据获取失败');
      } finally {
        loading.value = false;
      }
    };
    //修改状态
    const onStatusChange = async (row) => {
      const updatedStatus = row.cp_state === 1 ? 0 : 1;
      try {
        await axios.put(`${API_URL}/UpdateStatus?cp_code=${row.cp_code}&cp_state=${updatedStatus}&update_by=${sessionStorage.getItem('u')}`);
        row.cp_state = updatedStatus; // 更新本地状态  
        ElMessage.success('状态更新成功');
      } catch (error) {
        console.error('状态更新失败:', error);
        ElMessage.error('状态更新失败');
      }
    };

    const filteredTableData = computed(() => {
      let data = tableData.value;
      // 分页  
      const start = (currentPage.value - 1) * pageSize.value;
      return data.slice(start, start + pageSize.value);
    });
    //显示bom详情
    const showBOMDetails = (row) => {
      router.push({ path: '/BomXq', query: { bomcode: row.bom_code } });
    };
    //删除
    const confirmDelete = (row) => {
      ElMessageBox.confirm('确定删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          axios
            .put(`/api/BD_CP/UpdateDelete?cp_code=${row.cp_code}&isdelete=0&update_by=${sessionStorage.getItem('u')}`)
            .then(() => {
              ElMessage.success('删除成功!');
              fetchData(); // 重新加载数据
            })
            .catch(() => {
              ElMessage.error('删除失败');
            });
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除'
          });
        });
    };
    //新增 修改按钮
    const openDialog = (action, row = {}) => {
      if (action === 'edit') {
        router.push({ path: '/UpdateProductFrom', query: { productId: row.cp_code } });
      } else {
        router.push('/ProductForm');
      }
    };

    const deleteRow = (row) => {
      const index = tableData.value.indexOf(row);
      if (index > -1) {
        tableData.value.splice(index, 1);
        totalItems.value = tableData.value.length; // 更新总数  
      }
    };
    //导入
    const importData = () => {
      console.log('Importing data...');
    };
    //查看
    const ck = (row) => {
      router.push({ path: '/CheckProductForm', query: { productId: row.cp_code } });
    };
    //搜索
    const query = () => {
      console.log('Querying with:', searchTable.value);
    };

    const reset = () => {
      searchTable.value = ''; // 重置搜索框  
      selectedFilter.value = ''; // 重置选择器  
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      console.log('Current page:', page);
    };

    //初始化数据获取  
    fetchData();

    return {
      filteredTableData,
      loading,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      openDialog,
      confirmDelete,
      importData,
      query,
      handleCurrentChange,
      reset,
      onStatusChange,
      showBOMDetails,
      ck
    };
  },
};  
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 95%;
  background-color: rgba(255, 255, 255, 0.5); /* 设置表格背景色为白色，并带有50%的透明度 */
}
.el-pagination {  
  margin-bottom: 10px; /* 设置下边距为10px */  
  margin-top: 5px;     /* 设置上内边距为5px */ 
}  
</style>